package cn.zlj.pethome.user.service.impl;

import cn.zlj.pethome.basic.config.BussinessException;
import cn.zlj.pethome.basic.contant.BaseConstants;
import cn.zlj.pethome.basic.domain.Logininfo;
import cn.zlj.pethome.basic.mapper.LogininfoMapper;
import cn.zlj.pethome.basic.util.MD5Utils;
import cn.zlj.pethome.basic.util.StrUtils;
import cn.zlj.pethome.user.domain.User;
import cn.zlj.pethome.user.dto.EmailRegisterDto;
import cn.zlj.pethome.user.dto.PhoneRegisterDto;

import cn.zlj.pethome.user.mapper.UserMapper;
import cn.zlj.pethome.user.service.RegisterDtoService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.Date;

@Service
public class RegisterDtoServiceImpl implements RegisterDtoService {
    @Autowired
    private JavaMailSender javaMailSender;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private LogininfoMapper logininfoMapper;

    @Override
    public void register(PhoneRegisterDto registerDto) {
        //判断数据
        extracted(registerDto);
        //先加入logininfo user
        User user = SetUser(registerDto);
        Logininfo logininfo=new Logininfo();
        BeanUtils.copyProperties(user,logininfo);
        //添加
        logininfoMapper.add(logininfo);
        user.setLogininfoId(logininfo.getId());
        userMapper.add(user);


    }

    @Override
    public void registerEmail(EmailRegisterDto emailRegisterDto) {
        //判读数据是否为空
        //判断两次密码是否一致
        if (!emailRegisterDto.getPassword().equals(emailRegisterDto.getPasswordRepeat())){
            throw new BussinessException("两次输入密码不一致");
        }
        //判断邮箱是否被注册
        User email = userMapper.findByEmail(emailRegisterDto.getEmail());
        if(email==null){
            throw new BussinessException("已经注册去登陆");
        }
        //最后发送邮件
        //发送邮件
        // 1.创建复杂邮件对象
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        // 2.发送复杂邮件的工具类
        MimeMessageHelper helper = null;
        try {
            helper = new MimeMessageHelper(mimeMessage,true,"utf-8");
            helper.setFrom("z1056085512@qq.com");
            helper.setSubject("宠物之家注册结果通知");
            // 3.设置文本内容，第二个参数 true 代表是否是一个html内容
            helper.setText("<h1>点击下方链接注册成功</h1>"+"http://localhost:8080/user/emailRegister?eamil="+emailRegisterDto.getEmail()+"&password="+email.getPassword(),true);
            helper.setTo(emailRegisterDto.getEmail());
        } catch (MessagingException e) {
            e.printStackTrace();
        }
        // 6.发送邮件
        javaMailSender.send(mimeMessage);
    }

    private User SetUser(PhoneRegisterDto t){
        String salt=StrUtils.getRandomString(32);
        String pwd=salt+t.getPassword();
        pwd= MD5Utils.encrypByMd5(pwd);
        return User
                .builder()
                .username(t.getPhone())
                .phone(t.getPhone())
                .state(1)
                .password(pwd)
                .salt(salt)
                .createtime(new Date())
                .build()
                ;

    }
     //数据验证
    private void extracted(PhoneRegisterDto registerDto) {
        if(!registerDto.getPassword().equals(registerDto.getPasswordRepeat())){
            throw new BussinessException("两次密码不一致");
        }
        //验证码是否一致 手机是否一致
        String RedisSmsCode = (String) redisTemplate.opsForValue().get(String.format(BaseConstants.VerifyCodeConstants.BUSINESS_REGISTER_PREFIX, registerDto.getPhone()));
        if(StringUtils.isBlank(RedisSmsCode)){
            throw new BussinessException("验证码错误");
        }
        String[] Redis=RedisSmsCode.split(":");
        String RedisPhone=Redis[1];
        if(!RedisPhone.equals(registerDto.getPhone())){
            throw new BussinessException("手机号不一致");
        }
        if(!Redis[0].equals(registerDto.getSmsCode())){
            throw new BussinessException("验证码错误");
        }
        //是否注册过
        User user = userMapper.findByPhone(registerDto.getPhone());
        if(user!=null){
            throw new BussinessException("滚去登录");
        }
    }
}
